package com.hwl.lab.controller;

import com.hwl.lab.entity.RoleAndMenu;
import com.hwl.lab.entity.User;
import com.hwl.lab.entity.UserAndRole;
import com.hwl.lab.repository.RoleAndMenuRepository;
import com.hwl.lab.repository.RoleRepository;
import com.hwl.lab.repository.UserAndRoleRepository;
import com.hwl.lab.service.UserService;
import com.hwl.lab.unit.Usercache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@CrossOrigin //允许跨域请求
@RestController
public class LoginController {
    @Autowired
    private UserService userService;
    @Autowired
    private Usercache usercache;
    @Autowired
    private UserAndRoleRepository userAndRoleRepository;
    @Autowired
    private RoleAndMenuRepository roleAndMenuRepository;
    @Autowired
    private RoleRepository roleRepository;
    // 登录
    @PostMapping("/login/{userid}/{pwd}")
    public String login(@PathVariable("userid") String userid,@PathVariable("pwd") String pwd) {
        User user = userService.findByUseridA(userid);
        if (user == null) {
            return "账号不存在";
        } else if (!user.getPwd().equals(pwd)) {
            return "密码不正确";
        } else if (user.getStatus().equals("禁用")) {
            return "该用户已被禁用";
        } else {
            usercache.UserMegs(userid);
            return "登录成功";
        }
    }
    //获取用户信息
    @GetMapping("/getuser")
    public User getuser() {
        return usercache.getUser();
    }
    // 获取用户权限
    @GetMapping("/getmenus/{userid}")
    public String[] menus(@PathVariable("userid") String userid) {
        List<UserAndRole> list = userAndRoleRepository.findRolenameByUserid(userid);//获取用户角色
        int length = list.size();
        String[] rolelist = new String[length];
        for (int i =0;i<length;i++){
            rolelist[i] =  roleRepository.findByRolename(list.get(i).getRolename()).getRoleid();
            System.out.println(rolelist[i]);
        }
        int length_m=0;
        List<RoleAndMenu> menulists = new ArrayList<>();
        for (int i=0;i<length;i++) {
            length_m=length_m+roleAndMenuRepository.findMneunameByRoleid(rolelist[i]).size();
            menulists.addAll(roleAndMenuRepository.findMneunameByRoleid(rolelist[i]));
        }
        String[] menulist = new String[length_m];
        for (int i = 0;i<length_m;i++) {
            menulist[i] = menulists.get(i).getMenuname();
            System.out.println(menulist[i]);
        }
        return menulist;
    }
}
